<template>
  

    <el-button
            :size="size"
            :type="type"
            :icon="icon"
            :plain="plain"
            @click="handleClick"
            :loading="loading">
              <slot></slot>
            </el-button>
    
</template>


<script>

  import Http from '../../kit/HttpKit'
  import Api from '../../api/Api'

  export default {
    data() {
      return {
        loading: false
      }
    },
    props: ['size', 'icon', 'plain', 'type', 'refForm', 'postOption', 'beforeSubmit'],
    methods: {
      handleClick(){
        let beforeSubmit = this.beforeSubmit;
        if (beforeSubmit) {
          beforeSubmit();
        }
        let obj = this.postOption;
        
        if (this.refForm != undefined) {
          let refForm = this.refForm();
          refForm.validate(valid => {
            if (valid) {

              this.doPost(obj);
              
            }
          });
        }else {
          this.doPost(obj);
        }
        
      },
      doPost(obj){

        let startTime = new Date().getTime();
        this.loading = true;
        let data = obj.data;
        if (data == undefined || data == ''){
          data = {};
        }
        data.api_token = Api.getApiToken();
        data.api_user_id = Api.getApiUserId();

        Http.post(obj.url, data, json=>{
           
          let curTime = new Date().getTime();
          if (curTime - startTime > 500) {
            this.loading = false;

            Api.getDataCB(json, json=>{
              if (obj.callback != undefined) {
                obj.callback(json);
                document.activeElement.blur();
              }
            });

          }else {
            setTimeout(()=>{
              this.loading = false;

              Api.getDataCB(json, json=>{
                if (obj.callback != undefined) {
                  obj.callback(json);
                  document.activeElement.blur();
                }
              });

            }, 500 - (curTime - startTime));
          }

        });
      }
    }
  }
</script>

<style type="text/css">
  
</style>
